<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="90px" v-loading="formLoading">
      <el-form-item label="项目名称" prop="projectId">
        <el-select v-model="formData.projectId" placeholder="请选择项目名称" class="!w-340px">
          <el-option v-for="dict in projectOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="任务名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入任务名称" class="!w-340px" />
      </el-form-item>
      <el-form-item label="任务类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择任务类型" @change="handleSelectChange" class="!w-340px">
          <el-option v-for="dict in getDictOptions(DICT_TYPE.BPM_TASK_TYPE)" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="流程定义" v-if="showSelect1" prop="processDefinitionId">
        <el-tree-select @node-click="(e) => chooseForm(e)" v-model="formData.processDefinitionId" placeholder="请选择流程定义"
          :data="processDefinitionOptions" :render-after-expand="false" class="!w-340px" />
      </el-form-item>
      <el-form-item label="标准流程" v-if="showSelect2" prop="processDefinitionId">
        <el-tree-select v-model="formData.processDefinitionId" :data="processDefinitionOptions"
          :render-after-expand="false" :disabled="true" class="!w-340px" />
      </el-form-item>
      <div v-if="showSelect2">
        <el-form-item v-for="userTask in startUserSelectTasks" :key="userTask.id" :label="userTask.name"
          :prop="'startUserSelectAssignees.' + userTask.id">
          <el-tree-select :props="defaultProps" @change="vailUser(userTask.id)"
            v-model="formData.startUserSelectAssignees[userTask.id]" :data="userList" multiple
            :render-after-expand="false" placeholder="请选择审批人" class="!w-340px" />
        </el-form-item>
      </div>
      <el-form-item v-if="showSelect1" label="负责人" prop="adminId">
        <el-tree-select :props="defaultProps" v-model="formData.adminId" :data="userList" :render-after-expand="false"
          placeholder="请选择负责人" class="!w-340px" />
      </el-form-item>
      <el-form-item v-if="showSelect1" label="确认人" prop="confirmId">
        <el-tree-select :props="defaultProps" v-model="formData.confirmId" :data="userList" :render-after-expand="false"
          placeholder="请选择确认人" class="!w-340px" />
      </el-form-item>
      <el-form-item v-if="showSelect1" label="关注人" prop="attentionId">
        <el-tree-select :props="defaultProps" v-model="formData.attentionId" :data="userList"
          :render-after-expand="false" placeholder="请选择关注人" class="!w-340px" />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker v-model="formData.startTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择计划开始时间" class="!w-340px" />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker v-model="formData.endTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择计划结束时间" class="!w-340px" @change="handleEndTimeChange" />
      </el-form-item>
      <el-form-item label="计划天数">
        <span>{{ planDays }}</span>
      </el-form-item>
      <el-form-item label="任务标签" prop="tagId">
        <el-tree-select v-model="formData.tagId" placeholder="请选择标签" :data="options" :render-after-expand="false"
          class="!w-340px" />
      </el-form-item>
      <el-form-item label="父&nbsp;&nbsp;任&nbsp;务" prop="parentId">
        <el-input v-model="formData.parentId" placeholder="请输入父任务" class="!w-340px" />
      </el-form-item>
      <el-form-item label="关联任务" prop="relationId">
        <el-input v-model="formData.relationId" placeholder="请输入关联任务" class="!w-340px" />
      </el-form-item>
      <el-form-item label="任务描述" prop="description">
        <el-input v-model="formData.description" placeholder="请输入任务描述" class="!w-340px" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <Dialog v-model="detailVisible" title="表单详情" width="800">
    <form-create :option="detailData.option" :rule="detailData.rule" />
  </Dialog>
</template>
<script setup lang="ts">
import { TaskInfoApi, TaskInfoVO } from '@/api/bpm/taskinfo'
import { DICT_TYPE, getDictOptions } from '@/utils/dict'
import * as UserApi from '@/api/system/user'
import { TagGroupInfoApi, TagGroupInfoVO } from '@/api/bpm/taggroupinfo'
import * as DefinitionApi from '@/api/bpm/definition'
import * as FormApi from '@/api/bpm/form'
import { setConfAndFields2 } from '@/utils/formCreate'
import { number } from 'vue-types'
import { ProjectInfoApi } from '@/api/bpm/projectinfo'

/** 流程任务信息 表单 */
defineOptions({ name: 'TaskInfoForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formId = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  code: undefined,
  name: undefined,
  type: undefined,
  formId: undefined,
  adminId: undefined,
  confirmId: undefined,
  attentionId: undefined,
  status: undefined,
  startTime: undefined,
  endTime: undefined,
  tagId: undefined,
  processDefinitionId: undefined,
  parentId: undefined,
  relationId: undefined,
  description: undefined,
  orderRank: undefined,
  variables: {},
  planDays: undefined,
  projectId: undefined,
  startUserSelectAssignees: {},
})
const formRef = ref() // 表单 Ref

// 表单验证
const formRules = reactive({
  projectId: [{ required: true, message: '项目名称不能为空', trigger: 'change' }],
  name: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '任务类型不能为空', trigger: 'change' }],
  processDefinitionId: [{ required: true, message: '流程定义不能为空', trigger: 'change' }],
  adminId: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
  confirmId: [{ required: true, message: '确认人不能为空', trigger: 'blur' }],
  attentionId: [{ required: true, message: '关注人不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '开始时间不能为空', trigger: 'change' }],
  endTime: [{ required: true, message: '结束时间不能为空', trigger: 'change' }],
  'startUserSelectAssignees.Activity_0ywahep': [{ required: true, message: '审批人不能为空', trigger: 'blur' }],
  'startUserSelectAssignees.Activity_0i8dgjt': [{ required: true, message: '审批人不能为空', trigger: 'blur' }],
})
// const dynamicRules = reactive({
//   'startUserSelectAssignees.Activity_0ywahep': [{ required: true, message: '审批人不能为空', trigger: 'blur' }],
//   'startUserSelectAssignees.Activity_0i8dgjt': [{ required: true, message: '审批人不能为空', trigger: 'blur' }],
// })

const vailUser = async (value) => {
  await formRef.value.validateField('startUserSelectAssignees.' + value);
}


//打开弹窗默认流程定义和表单下拉选不显示
const showSelect1 = ref(false) //流程定义
const showSelect2 = ref(false) //表单
const startUserSelectTasks = ref([]) // 发起人需要选择审批人的用户任务列表

//控制显示哪个
const handleSelectChange = async (value) => {
  formData.value.startUserSelectAssignees = {}
  formData.value.adminId = undefined;
  formData.value.confirmId = undefined;
  formData.value.attentionId = undefined;
  showSelect1.value = value === '2'
  showSelect2.value = value === '1'
  if (value == 1) {
    startUserSelectTasks.value = [];
    const item = processDefinitionOptions.value.find(item => item.label === "标准任务流程");
    formData.value.processDefinitionId = item.id
    let formId = item.formId;
    chooseForm({ formId: formId })
    const processDefinitionDetail = await DefinitionApi.getProcessDefinition(formData.value.processDefinitionId)
    if (processDefinitionDetail) {
      startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks
    }
    console.log(startUserSelectTasks.value, 'startUserSelectTasks.value');

  } else {
    formData.value.processDefinitionId = undefined
  }
}

//负责人下拉选
const userList = ref<any>([]) // 用户列表
const defaultProps = ref({
  children: "childrenDepts",
  label: "deptName",
  value: 'id'
})

const getUserList = async () => {
  const response = await UserApi.getSimpleUserListCopy()
  userList.value = response.map(item => {
    item.childrenDepts = item.childrenDepts.concat(
      fmtUserName(item.childrenUsers) || []
    );
    return {
      ...item,
      childrenDepts:
        item.childrenDepts && item.childrenDepts.length
          ? item.childrenDepts.map(it => {
            return getEndDepartments(it);
          })
          : fmtUserName(item.childrenUsers) || []
    };
  }
  );
}

const getEndDepartments = (obj: any) => {
  if (!obj.childrenDepts || obj.childrenDepts.length == 0) {
    obj.childrenDepts = fmtUserName(obj.childrenUsers);
  } else {
    obj.childrenDepts = obj.childrenDepts
      .concat(fmtUserName(obj.childrenUsers) || [])
      .map(item => {
        return getEndDepartments(item);
      });
  }
  return obj;
}

const fmtUserName = (childrenUsers) => {
  if (!childrenUsers || !childrenUsers.length) return []
  return childrenUsers.map(item => {
    return {
      ...item,
      deptName: item.nickname || ''
    }
  });
}

//标签组下拉选
const cascaderValue = ref([])
const options = ref([])

const projectOptions = ref([
  {
    value: undefined,
    label: undefined
  }
]) // 项目列表

const getProjectInfo = async () => {
  let params = {
    pageNo: 1,
    pageSize: 100
  }
  let response = await ProjectInfoApi.getProjectInfoPage(params)
  projectOptions.value = response.list.map((item) => ({
    value: item.id,
    label: item.name
  }))
}

const getAllTagInfo = async () => {
  let response = await TagGroupInfoApi.getAllTagGroupInfo()
  options.value = response.map((tagGroup) => ({
    value: tagGroup.id,
    label: tagGroup.name,
    children: tagGroup.children.map((tag) => ({
      value: tag.tagId,
      label: tag.tagName
    }))
  }))
}

// 流程定义的列表
const processDefinitionOptions = ref([])
const getAllProcessDefinition = async () => {
  let response = await DefinitionApi.getProcessDefinitionList({ suspensionState: 1 })
  processDefinitionOptions.value = response.map((processDefinition) => ({
    value: processDefinition.id,
    label: processDefinition.name,
    formId: processDefinition.formId,
    id: processDefinition.id
  }))
}

// 表单列表
const formOptions = ref([])
const getAllForm = async () => {
  let response = await FormApi.getFormSimpleList()
  formOptions.value = response.map((formOption) => ({
    value: formOption.id,
    label: formOption.name
  }))
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formId.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await TaskInfoApi.getTaskInfo(id)
    } finally {
      formLoading.value = false
    }
  }
  //打开页面重置控制变量
  showSelect1.value = false
  showSelect2.value = false
  //获取标签数据
  getAllTagInfo()
  //获取用户数据
  getUserList()
  //获取流程定义
  getAllProcessDefinition()
  //获取表单列表
  getAllForm()
  getProjectInfo()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as TaskInfoVO
    if (formId.value === 'create') {
      await TaskInfoApi.createTaskInfo(data)
      message.success(t('common.createSuccess'))
    } else {
      await TaskInfoApi.updateTaskInfo(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    //提交表单后重置变量
    showSelect1.value = false
    showSelect2.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    code: undefined,
    name: undefined,
    type: undefined,
    formId: undefined,
    adminId: undefined,
    confirmId: undefined,
    attentionId: undefined,
    status: undefined,
    startTime: undefined,
    endTime: undefined,
    tagId: undefined,
    processDefinitionId: undefined,
    parentId: undefined,
    relationId: undefined,
    description: undefined,
    orderRank: undefined,
    variables: {},
    planDays: undefined,
    projectId: undefined,
    startUserSelectAssignees: {},
  }
  formRef.value?.resetFields()
  //重置表单后重置变量
  showSelect1.value = false
  showSelect2.value = false
}

/** 计划天数 */
const planDays = computed(() => {
  if (formData.value.startTime && formData.value.endTime) {
    const start = new Date(formData.value.startTime)
    const end = new Date(formData.value.endTime)
    const diffTime = Math.abs(end - start)
    const diffDays = diffTime / (1000 * 60 * 60 * 24) // 差距的天数（包含小数部分）
    const roundedDiffDays = diffDays.toFixed(1) // 将差距的天数四舍五入到一位小数
    return parseFloat(roundedDiffDays) || 1.0 // 转换为浮点数，并确保至少为1天
  } else {
    return 1.0 // 默认情况下，返回1.0天
  }
})

const handleEndTimeChange = () => {
  formData.value.planDays = planDays.value
}

/** 详情操作 */
const detailVisible = ref(false)
const detailData = ref({
  rule: [],
  option: {}
})
formData.value.id = undefined
const onSubmit = (fApi) => {
  fApi
    .validate()
    .then(() => {
      formData.value.variables = fApi.formData()
      detailVisible.value = false
    })
    .catch(() => {
      console.log('未通过')
    })
}
const chooseForm = async (item: any) => {
  let query = 0
  // if (selectType == 'showSelect1') {
  formData.value.formId = undefined
  query = item.formId
  // } else {
  //   formData.value.processDefinitionId = undefined
  //   query = item.value
  // }
  const data = await FormApi.getForm(query)
  let conf = JSON.parse(data.conf)
  conf.submitBtn = {
    ...conf.submitBtn,
    click: onSubmit
  }
  data.conf = conf
  setConfAndFields2(detailData, data.conf, data.fields)
  // 弹窗打开
  detailVisible.value = true
}
</script>
